/**
 * 
 */

$(document).ready(function() {
	
	//retrieve user information
	updateUserData();
	
	// handle events
	$("#btn-user-logout").click(function() {
		logoutUser();
	});
	
});

function processResponseErrors(response) {
	var successful = response.responseSuccessful; 
	if(!successful) {
		//TODO paint user session errors
		alert(response.responseErrors);
		window.location = 'mobileEmulatorLogin.jsp';
	}
	return successful;
}

function updateUserData() {
	var userId = $.getCookie("geoserverudima.userId");
	var sessionToken = $.getCookie("geoserverudima.sessionToken");
	
	$.ajax({
		url : "../rest/users",
	    type: "POST",
	    contentType: "application/json",
	    dataType: "json",
	    data : JSON.stringify({
	    	"userId": userId,
	    	"userSession": {"userId": userId, "sessionToken": sessionToken} }),
	    success: function(data, textStatus, jqXHR) {
	    	paintHelloHeader(data);
	    },
	    error: function (jqXHR, textStatus, errorThrown) {
	 
	    }
	});
}

function paintHelloHeader(data) {
	if(processResponseErrors(data)) {
		var user = data.user;
		$("#div-hello-user-text").html("Hola, " + user.firstName + " " + user.lastName + " (" + user.userName + ")");
	}
}

function logoutUser() {
	var userId = $.getCookie("geoserverudima.userId");
	var sessionToken = $.getCookie("geoserverudima.sessionToken");
	
	$.ajax({
	    url : "../rest/users/logout",
	    type: "POST",
	    contentType: "application/json",
	    dataType: "json",
	    data : JSON.stringify({ "userSession": {"userId": userId, "sessionToken": sessionToken} }),
	    success: function(data, textStatus, jqXHR) {
	        document.cookie = "geoserverudima.userId=''";
	        document.cookie = "geoserverudima.sessionToken=''";
	        window.location = "mobileEmulatorLogin.jsp";
	    },
	    error: function (jqXHR, textStatus, errorThrown) {
	 
	    }
	});
}

